<template>
  <Dialog
    v-model:visible="dialog.visible"
    modal
    :header="dialog.title ? dialog.title : '请正对摄像头'"
    @show="openHandler"
    @hide="closeHandler"
  >
    <el-image v-show="image" :src="image" style="width: 640px; height: 480px" />
    <j-face-camera ref="faceCamera" v-show="!image" />

    <template v-if="showButton" #footer>
      <Button @click="dialog.visible = false">取消</Button>
      <Button v-if="!image" @click="takePhotoHandler">拍照</Button>

      <template v-else>
        <Button severity="secondary" @click="image = ''">重拍</Button>
        <Button @click="confirmHandler">确认</Button>
      </template>
    </template>
  </Dialog>
</template>
<script>
import JFaceCamera from './index'

export default {
  emits: ['success'],
  props: {
    dialog: {
      type: Object,
      required: true,
    },
    showButton: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      image: '',
    }
  },
  components: {
    JFaceCamera,
  },
  methods: {
    openHandler() {
      this.$nextTick(() => {
        this.tracking()
      })
    },
    closeHandler() {
      this.stop()
    },
    tracking() {
      this.$refs.faceCamera.tracking()
    },
    stop() {
      this.image = ''
      // this.$refs.faceCamera.stop()
    },
    takePhotoHandler() {
      this.$refs.faceCamera.capture().then((value) => {
        if (!value) {
          this.$message.warning('没有检测到人脸')
          return
        }

        this.image = value
      })
    },
    confirmHandler() {
      this.dialog.value = this.image
      this.dialog.visible = false

      this.$emit('success', this.image)
    },
  },
}
</script>
<style lang="scss">
.faceCameraDialog {
  width: 680px;
  height: 660px;
}
</style>
